package com.tduck.cloud.form.util;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhaoling
 * @date 2023年03月28日 10:35
 */
public class MergeMapUtil {
    public static void mergeMap(Map<String, Object> resultMap, Map<String, Object> currentMap, boolean flag, List<String> mydOptionsList) {
        // 权重总和
        int totalSatisfactionWeight = 0;
        if (flag) {
            for (String key : currentMap.keySet()) {
                if (!key.equals("name")) {
                    if (currentMap.get(key) instanceof Map) {
                        Map<String, Integer> currentRating = (Map<String, Integer>) currentMap.get(key);
                        Map<String, Integer> resultRating = (Map<String, Integer>) resultMap.get(key);
                        for (String ratingKey : currentRating.keySet()) {
                            resultRating.put(ratingKey, resultRating.getOrDefault(ratingKey, 0) + currentRating.get(ratingKey));
                        }
                    }
                }
            }
        } else {
            List<String> collect = mydOptionsList.stream().distinct().collect(Collectors.toList());
            for (String key : currentMap.keySet()) {
                if (!key.equals("name")) {
                    for (String s : collect) {
                        if (key.equals(s)) {
                            if (currentMap.get(key) instanceof Integer) {
                                Integer currentRating = (Integer) currentMap.get(key);
                                Integer resultRating = (Integer) resultMap.get(key);
                                resultMap.put(key, resultRating + currentRating);
                            }
                        }
                    }
                }
            }
        }
        double currentMapSatisfaction = Double.parseDouble(currentMap.get("satisfaction").toString());
        int currentRating = Integer.parseInt(currentMap.get("satisfactionWeight").toString());
        double resultMapSatisfaction = Double.parseDouble(resultMap.get("satisfaction").toString());
        int resultRating = Integer.parseInt(resultMap.get("satisfactionWeight").toString());
        totalSatisfactionWeight = currentRating + resultRating;
        resultMap.put("satisfactionWeight", totalSatisfactionWeight);
        resultMap.put("satisfaction", (currentMapSatisfaction * currentRating + resultMapSatisfaction * resultRating) / totalSatisfactionWeight);
    }
}
